package com.jy.api.service.impl;

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.BatchSmsAttributes;
import com.aliyun.mns.model.MessageAttributes;
import com.aliyun.mns.model.RawTopicMessage;
import com.aliyun.mns.model.TopicMessage;
import com.jy.api.service.AliSmsService;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by Administrator on 2017/7/1.
 */
@Service
@NoArgsConstructor
public class AliSmsServiceImpl implements AliSmsService {

    private static Logger logger = LoggerFactory.getLogger(AliSmsServiceImpl.class);

    @Value("${sms.accountendpoint}")
    private String accountEndpoint;

    @Value("${sms.accesskeyid}")
    private String ACCESS_KEY_ID;

    @Value("${sms.accesskeysecret}")
    private String ACCESS_KEY_SECRET;

    public AliSmsServiceImpl(String accountEndpoint, String ACCESS_KEY_ID, String ACCESS_KEY_SECRET) {
        this.accountEndpoint = accountEndpoint;
        this.ACCESS_KEY_ID = ACCESS_KEY_ID;
        this.ACCESS_KEY_SECRET = ACCESS_KEY_SECRET;
    }

    private static final String TOPIC_REF = "sms.topic-cn-hangzhou";

    private static final String FREE_SIGN_NAME = "火星捕手";

    /**
     * @param mobile
     * @param params
     */
    @Override
    public void sendSms(String mobile, Map<String, Object> params, String templateCode) {
        CloudAccount account = new CloudAccount(ACCESS_KEY_ID, ACCESS_KEY_SECRET, accountEndpoint);
        MNSClient client = account.getMNSClient();
        CloudTopic topic = client.getTopicRef(TOPIC_REF);
        /**
         * Step 2. 设置SMS消息体（必须）
         *
         * 注：目前暂时不支持消息内容为空，需要指定消息内容，不为空即可。
         */
        RawTopicMessage msg = new RawTopicMessage();
        msg.setMessageBody("sms-message");
        /**
         * Step 3. 生成SMS消息属性
         */
        MessageAttributes messageAttributes = new MessageAttributes();
        BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();
        // 3.1 设置发送短信的签名（SMSSignName）
        batchSmsAttributes.setFreeSignName("成都火星云网络");
        // 3.2 设置发送短信使用的模板（SMSTempateCode）
        batchSmsAttributes.setTemplateCode(templateCode);
        // 3.3 设置发送短信所使用的模板中参数对应的值（在短信模板中定义的，没有可以不用设置）
        BatchSmsAttributes.SmsReceiverParams smsReceiverParams = new BatchSmsAttributes.SmsReceiverParams();
        for (Map.Entry<String, Object> param : params.entrySet()) {
            smsReceiverParams.setParam(param.getKey(), param.getValue().toString());
        }
        // 3.4 增加接收短信的号码
        batchSmsAttributes.addSmsReceiver(mobile, smsReceiverParams);
        messageAttributes.setBatchSmsAttributes(batchSmsAttributes);
        try {
            /**
             * Step 4. 发布SMS消息
             */
            TopicMessage ret = topic.publishMessage(msg, messageAttributes);

        } catch (ServiceException se) {
            logger.error("Sms is ServiceException:{}", se);
            se.printStackTrace();
        } catch (Exception e) {
            logger.error("Sms is error:{}", e);
            e.printStackTrace();
        }
        client.close();
    }


}
